package com.leTest.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.leTest.exceptionhandler.CustomExceptionHandler;
import com.leTest.service.VodService;
import com.leTest.utils.ConstantVodUtils;
import com.leTest.utils.InitVodClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadAlyVideo(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String title = fileName.substring(fileName.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(
                    ConstantVodUtils.ACCESS_KEY_ID,
                    ConstantVodUtils.ACCESS_KEY_SECRET,
                    title,
                    fileName,
                    inputStream
            );
            UploadVideoImpl uploadVideo = new UploadVideoImpl();
            UploadStreamResponse response = uploadVideo.uploadStream(request);
            String videoId = "";
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else {
                videoId = response.getVideoId();
            }

            return videoId;
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //根据多个视频id删除阿里云中的视频
    @Override
    public void removeMoreAlyVideo(List videoIdList) {
        try {
            //1.创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(
                    ConstantVodUtils.ACCESS_KEY_ID,
                    ConstantVodUtils.ACCESS_KEY_SECRET);

            //2.创建删除的request
            DeleteVideoRequest request = new DeleteVideoRequest();

            //3.向request对象里面设置视频id
            //①需要先将videoIdList集合中的id遍历为1,2,3的形式
            String videoIds = StringUtils.join(videoIdList.toArray(), ",");
            //②设置视频id
            request.setVideoIds(videoIds);

            //4.调用初始化对象里面的方法,实现删除
            client.getAcsResponse(request);
        } catch(Exception e) {
            e.printStackTrace();
            throw new CustomExceptionHandler(100, "删除视频失败");
        }
    }

}

